package com.link4a.doms.web.auth;

import com.link4a.doms.model.User;
import com.link4a.doms.web.SessionContext;
import com.link4a.doms.web.UserWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author brown
 */
public final class AuthMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Autowired
	private SessionContext sessionContext;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(Auth.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

		UserWrapper user = sessionContext.getUserWrapper();
		
		Class<?> parameterType = parameter.getParameterType();
		if (parameterType == User.class) {
			return user.getUser();
		} else if (parameterType == UserWrapper.class) {
			return user;
		} else {
			throw new Exception("unresolvable parameter type: " + parameterType);
		}
	}

}
